package com.lkeqi.tags.controller;

import com.lkeqi.tags.common.BaseResponse;
import com.lkeqi.tags.constant.Constant;
import com.lkeqi.tags.dto.UserDto;
import com.lkeqi.tags.dto.request.RegisterRequestParam;
import com.lkeqi.tags.entity.User;
import com.lkeqi.tags.service.UserService;
import com.lkeqi.tags.utils.ResultUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public BaseResponse<User> login(@RequestBody UserDto userDto, HttpServletRequest request) {
        return userService.login(userDto.getUserNo(), userDto.getPwd(), request);
    }

    @PostMapping("/register")
    public BaseResponse<Long> register(@RequestBody RegisterRequestParam registerRequestParam) {
        return userService.userRegister(registerRequestParam);
    }

    @GetMapping("/currentUser")
    public BaseResponse<User> currentUser(HttpServletRequest request) {
        User currentUser = (User) request.getSession().getAttribute(Constant.USER_STATE_LOGIN);
        if (currentUser == null) {
            return null;
        }
        Long id = currentUser.getId();
        User user = userService.getById(id);
        User safeUser = userService.getSafeUser(user);
        return ResultUtils.success(safeUser);
    }

    @GetMapping("/list")
    public BaseResponse<List<User>> list(@RequestParam(value = "username", required = false) String username, HttpServletRequest request) {
        return userService.list(username, request);
    }


    @PostMapping("/delete")
    public BaseResponse delete(@RequestBody long id, HttpServletRequest request) {
        return userService.deleteById(id, request);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> delete(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        return userService.logout(request);
    }


}
